package scm.message;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

public class GestorMensaje {

    private JFileChooser fileChooser;
    private FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivo de Texto","txt");
    private File file = null;
    private boolean isopen =false;
    private ArrayList contenido = new ArrayList();
    private int index = 0; 
    
    private JTextField sender;
    private JTextField destinatario;
    private JTextField asusnto;
    private JTextField mensaje;

    public GestorMensaje(JTextField sender, JTextField destinatario, JTextField asunto, JTextField mensaje ){
        this.sender = sender;
        this.destinatario = destinatario;
        this.asusnto = asunto;
        this.mensaje = mensaje;
    }

    public void Guardar(String texto){
       fileChooser = new JFileChooser();
       fileChooser.setFileFilter(filter);
       int result = fileChooser.showSaveDialog(null);
       if ( result == JFileChooser.APPROVE_OPTION ){
            this.isopen = false;
            this.contenido.clear();
            this.index=1;
            if ( escribir( fileChooser.getSelectedFile(),  texto) ){
                JOptionPane.showMessageDialog(null, "Archivo '" + fileChooser.getSelectedFile().getName() + "' guardado ");
                this.isopen=true;
            }
        }
    }

    public void Adicionar(int clave, Message m){
        String texto = clave+ "," +m.obtenerSenderMensaje()+ "," + m.obtenerDestinatarioMensaje() + "," + m.devolverContenido().toString();
        if( this.file != null){
            if ( escribir( this.file ,  texto) )
                JOptionPane.showMessageDialog(null, "Archivo '" + this.file.getName() + "' actualizado ");
        }
        else
            Guardar( texto );
    }

    public void Abrir(){
        fileChooser = new JFileChooser();
        fileChooser.setFileFilter(filter);
        int result = fileChooser.showOpenDialog(null);
        if ( result == JFileChooser.APPROVE_OPTION ){
            this.file = fileChooser.getSelectedFile();
            leer( this.file );
            this.isopen=true;
        }
    }

    private boolean escribir(File fichero, String texto){
        boolean res=false;        
        PrintWriter writer = null;
        try {
            String f = fichero.toString();
            if(!f.substring( f.length()-4, f.length()).equals(".txt") ){
                f = f + ".txt";
                fichero = new File(f);
            }            
            writer = new PrintWriter( fichero );
            if( this.isopen ){  
                Iterator It = contenido.iterator();
                while (It.hasNext()){
                    writer.println( It.next() );
                }
                writer.println( texto );
                this.contenido.add(texto);
            }
            else 
            {
                this.contenido.add(texto);
                writer.println( texto );    
            }            
            this.file = fichero;
            writer.close();            
            res = true;
        } catch (FileNotFoundException ex) {
            System.out.println("Error:" + ex);
        } finally {
            writer.close();
        }
        return res;
    }

    public boolean leer( File fichero ){
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fichero));
            this.contenido.clear();
            String linea;
            while ( (linea = reader.readLine() ) != null)                
                this.contenido.add( linea );
            Siguiente();
            return true;
        } catch (IOException ex) {
            System.out.println("Error: " + ex);
        }  finally {
            try {
                reader.close();
            } catch (IOException ex) {
                System.out.println("Error: " + ex);
            }
        }
        return false;
    }

    public void Siguiente(){
        if( this.file != null ){
            this.index = (index>=contenido.size())? 1 : index + 1;
            int count =1;
            Iterator It = contenido.iterator();
            while (It.hasNext()){
                String tmp = It.next().toString();
                if( count == index){
                    String[] datos = tmp.split(",");
                    this.sender.setText(datos[1]);
                    this.destinatario.setText(datos[2]);
                    this.asusnto.setText(datos[3]);
                    this.mensaje.setText(datos[4]);
                    break;
                }
                count ++;
            }
        }
    }

    public void Siguiente(String nombre){
        if( this.file != null ){
            this.index = (index>=contenido.size())? 1 : index + 1;
            int count =1;
            Iterator It = contenido.iterator();
            while (It.hasNext()){
                String tmp = It.next().toString();
                if( count == index){
                    String[] datos = tmp.split(",");
                    if(datos[2].equals(nombre)){
                        this.sender.setText(datos[1]);
                        this.destinatario.setText(datos[2]);
                        this.asusnto.setText(datos[3]);
                        this.mensaje.setText(datos[4]);
                        break;
                    }
                }
                count ++;
            }
        }
    }

    public int Cantidad(String nombre){
        int cont = 0;
        if( this.file != null ){
            Iterator It = contenido.iterator();
            while (It.hasNext()){
                String tmp = It.next().toString();
                String[] datos = tmp.split(",");
                if(datos[2].equals(nombre)){
                    cont ++ ;
                }
            }
         }
         return cont;
    }

    public void AdicionarCliente(String texto){
        if( this.file != null){
            if ( escribir( this.file ,  texto) )
                JOptionPane.showMessageDialog(null, "Archivo '" + this.file.getName() + "' actualizado ");
        }
        else
            Guardar( texto );
    }

    
}
